package com.healthteches.write;

import de.beckhoff.jni.Convert;
import de.beckhoff.jni.JNIByteBuffer;
import de.beckhoff.jni.tcads.AdsCallDllFunction;
import de.beckhoff.jni.tcads.AmsAddr;

public class WriteByte {
  public static void main(String[] args) {
    long nPort, nErr;
    AmsAddr addr = new AmsAddr();
    JNIByteBuffer hdlBuff = new JNIByteBuffer(4);
    // Symbol name: String to byte[]
    JNIByteBuffer symBuff = new JNIByteBuffer(Convert.StringToByteArr("MAIN.PLCVar"));
    // JNIByteBuffer dataBuff = new JNIByteBuffer(4);

    byte[] dataVal = new byte[] {100};

    // Open communication
    nPort = AdsCallDllFunction.adsPortOpen();
    nErr = AdsCallDllFunction.getLocalAddress(addr);
    addr.setPort(801);
    if (nErr != 0) {
      System.out.println("Error: Open Communication: 0x" + Long.toHexString(nErr));
    }

    // Get handle by symbol name
    nErr =
        AdsCallDllFunction.adsSyncReadWriteReq(
            addr,
            0xF003,
            0x0,
            hdlBuff.getUsedBytesCount(),
            hdlBuff,
            symBuff.getUsedBytesCount(),
            symBuff);
    if (nErr != 0) {
      System.out.println("Error: Get handle: 0x" + Long.toHexString(nErr));
    }

    // Handle: byte[] to int
    int hdlBuffToInt = Convert.ByteArrToInt(hdlBuff.getByteArray());
    // Write value by handle
    nErr = AdsCallDllFunction.adsSyncWriteReqArray(addr, 0xF005, hdlBuffToInt, 0x1, dataVal);

    // Close communication
    nErr = AdsCallDllFunction.adsPortClose();
    if (nErr != 0) {
      System.out.println("Error: Close Communication: 0x" + Long.toHexString(nErr));
    }

    try {
      System.in.read();
    } catch (Exception e) {
      System.out.println("Error: Close program");
    }
  }
}
